package com.qiouchi.bootweb.controller;

import com.qiouchi.bootweb.dao.CategoryDao;
import com.qiouchi.bootweb.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class CategoryController {

    @Autowired
    CategoryDao categoryDao;

    @RequestMapping("listCategory")
    public String listCategory(Model model, @RequestParam(value = "start",defaultValue = "0")
                               int start,@RequestParam(value = "size",defaultValue = "5") int size) {
        start = start < 0 ? 0:start;
        Sort sort = new Sort(Sort.Direction.DESC,"id");
        Pageable pageable = new PageRequest(start,size,sort);
        Page<Category> page = categoryDao.findAll(pageable);

        System.out.println(page.getNumber());
        System.out.println(page.getNumberOfElements());
        System.out.println(page.getSize());
        System.out.println(page.getTotalElements());
        System.out.println(page.getTotalPages());

        model.addAttribute("page",page);

        return "listCategory";
    }

    @RequestMapping("/addCategory")
    public String addCategory(Category category){
        categoryDao.save(category);
        return "redirect:listCategory";
    }


    @RequestMapping("deleteCategory")
    public String deleteCategory(Category category){
        categoryDao.delete(category);
        return "redirect:listCategory";
    }

    @RequestMapping("editCategory")
    public String editCategory(int id,Model model){
        Category category = categoryDao.getOne(id);
        model.addAttribute("c",category);
        return "editCategory";
    }

    @RequestMapping("updateCategory")
    public String updateCategory(Category category){
        categoryDao.save(category);
        return "redirect:listCategory";
    }

}
